<template>
  <el-row style="margin-top: 15px">
    <el-col :span="12">
      <el-image src="/src/assets/img.jpg"/>
    </el-col>
    <el-col :span="12">
      <el-form label-width="auto" class="loginForm">
        <h1>用户登录</h1>
        <el-form-item>
          <el-input prefix-icon="User" placeholder="请输入用户名" v-model="userInfo.username"/>
        </el-form-item>
        <el-form-item>
          <el-input type="password" prefix-icon="Key" placeholder="请输入密码" v-model="userInfo.password"/>
        </el-form-item>
        <el-form-item>
          <el-input style="width: 175px; margin-right: 5px;" prefix-icon="Picture" placeholder="请输入验证码"
                    v-model="userInfo.captchaInput"/>
          <el-image :src="imageBase64Data" @click="getCaptcha"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="loginBtn" @click="login">登录</el-button>

        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import userApi from "@/api/userApi.js";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";

const tokenStore = useTokenStore()
const userStore = useUserStore()
const router = useRouter()
const imageBase64Data = ref(null);
//用户注册信息
const userInfo = ref({
  username: '',
  password: '',
  key: '',
  captchaInput: ''
})

//用户注册
function login() {
  userApi.login(userInfo.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //保存token
          tokenStore.updateToken(resp.data);
          //获取用户信息
          getInfo();
          //跳转页面
          router.push("/user/index");
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

function getCaptcha() {
  userApi.captcha()
      .then(resp => {
        userInfo.value.key = resp.data.key;
        imageBase64Data.value = resp.data.imageBase64Data
      });
}

function getInfo() {
  userApi.getInfo()
      .then(resp => {
        if (resp.code == 10000) {
          //将已登陆用户信息保存在Pinia中
          userStore.updateUser(resp.data);
        }
      });
}
getCaptcha();
</script>

<style scoped>
.loginForm {
  width: 300px;
  margin: 45px 150px;
}

.loginForm h1 {
  text-align: center;
  margin-bottom: 20px;
}

.loginBtn {
  width: 100%;
}
</style>